<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="工单号" prop="orderNum">
        <el-input
          v-model="queryParams.orderNum"
          placeholder="请输入工单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->

      <!-- <el-form-item label="车牌号" prop="carNum">
        <el-input
          v-model="queryParams.carNum"
          placeholder="请输入车牌号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="操作人员" prop="createNickName">
        <el-input v-model="queryParams.createNickName" placeholder="请输入操作人员" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择工单状态" clearable size="small">
          <el-option v-for="dict in dict.type.order_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="司机姓名" prop="driverName">
        <el-input
          v-model="queryParams.driverName"
          placeholder="请输入司机姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="处理结果" prop="driverDealStatus">
        <el-select
          v-model="queryParams.driverDealStatus"
          placeholder="请选择司机处理结果"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in dict.type.driver_deal_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="主管姓名" prop="managerName">
        <el-input
          v-model="queryParams.managerName"
          placeholder="请输入主管姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="保洁姓名" prop="cleanerName">
        <el-input
          v-model="queryParams.cleanerName"
          placeholder="请输入保洁姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="处理结果" prop="cleanerDealStatus">
        <el-select
          v-model="queryParams.cleanerDealStatus"
          placeholder="请选择保洁员处理结果"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in dict.type.cleaner_deal_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="时间范围">
        <el-date-picker v-model="daterangeDataTime" :picker-options="pickerOptions" size="small" style="width: 340px"
          value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期"
          end-placeholder="结束日期"></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['work:order:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['work:order:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['work:order:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['work:order:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="left" />
      <el-table-column type="index" label="序号" width="60" align="left" />
      <!-- <el-table-column
        label="工单号"
        align="left"
        prop="orderNum"
        minWidth="160"
      /> -->
      <el-table-column label="工单生成时间" align="left" prop="orderTime" minWidth="180" />
      <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="工单状态" align="left" prop="orderStatus" minWidth="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_status" :value="scope.row.orderStatus" />
        </template>
      </el-table-column>
      <el-table-column label="设施" align="left" prop="facilityName" minWidth="120" />
      <!-- <el-table-column
        label="车牌号"
        align="left"
        prop="carNum"
        minWidth="120"
      /> -->
      <el-table-column label="司机姓名" align="left" prop="driverName" minWidth="120" />
      <el-table-column label="司机处理结果" align="left" prop="driverDealStatus" minWidth="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.driver_deal_status" :value="scope.row.driverDealStatus" />
        </template>
      </el-table-column>
      <el-table-column label="司机处理时间" align="left" prop="driverDealTime" width="180" />
      <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.driverDealTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="主管姓名" align="left" prop="managerName" minWidth="120" />
      <el-table-column label="保洁姓名" align="left" prop="cleanerName" minWidth="120" />
      <el-table-column label="保洁员处理结果" align="left" prop="cleanerDealStatus" minWidth="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.cleaner_deal_status" :value="scope.row.cleanerDealStatus" />
        </template>
      </el-table-column>
      <el-table-column label="保洁员处理时间" align="left" prop="cleanerDealTime" width="180" />
      <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.cleanerDealTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="备注" align="left" prop="remark" />
      <el-table-column label="操作人员" align="left" prop="createNickName" minWidth="120" />
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" minWidth="120">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['work:order:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['work:order:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改清运任务工单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="设施" prop="facilityId">
          <el-select v-model="form.facilityId" placeholder="请选择设施" style="width: 100%" @change="changeFacilityId">
            <el-option v-for="fac in facilityOptions" :key="fac.facilityId" :label="fac.facilityName"
              :value="fac.facilityId">
              <span style="float: left">{{ fac.facilityName }}</span>
              <span style="float: right; color: #909399">{{
                fac.address
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车辆部门" prop="carDeptId">
          <treeselect v-model="form.carDeptId" :options="deptOptions" :disable-branch-nodes="false" :show-count="true"
            placeholder="请选择车辆归属部门" :defaultExpandLevel="2" @input="changeCarDept" />
        </el-form-item>

        <el-form-item label="车辆" prop="teamSpanId">
          <el-select v-model="form.teamSpanId" placeholder="请选择车辆" style="width: 100%" @change="changeCarId">
            <el-option v-for="car in carOptions" :key="car.teamSpanId" :label="car.carNum" :value="car.teamSpanId">
              <span style="float: left">{{ car.carNum }}</span>
              <span style="float: right; color: #909399">{{
                `${car.teamSpanName} ${car.startSpan}-${car.endSpan}`
              }}</span>
              <span style="float: right; color: #909399; margin-right: 15px">{{
                car.personName
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="司机" prop="driverId">
          <el-input v-model="form.driverId" placeholder="请输入司机id" />
        </el-form-item> -->
        <el-form-item label="主管部门" prop="managerDeptId">
          <treeselect v-model="form.managerDeptId" :options="deptOptions" :disable-branch-nodes="false" :show-count="true"
            placeholder="请选择主管归属部门" :defaultExpandLevel="2" @input="changeManagerDept" />
        </el-form-item>

        <el-form-item label="主管" prop="managerId">
          <el-select v-model="form.managerId" placeholder="请选择主管" style="width: 100%" @change="changeManagerId">
            <el-option v-for="manager in managerOptions" :key="manager.personId" :label="manager.personName"
              :value="manager.personId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="保洁员部门" prop="deptId">
          <treeselect v-model="form.deptId" :options="deptOptions" :disable-branch-nodes="false" :show-count="true"
            placeholder="请选择归属部门" :defaultExpandLevel="2" @input="changeCleanerDept" />
        </el-form-item>

        <el-form-item label="保洁" prop="cleanerId">
          <el-select v-model="form.cleanerId" placeholder="请选择保洁人员" style="width: 100%" @change="changeCleanerId">
            <el-option v-for="cleaner in cleanerOptions" :key="cleaner.personId" :label="cleaner.personName"
              :value="cleaner.personId">
              <span style="float: left">{{ cleaner.personName }}</span>
              <span style="float: right; color: #909399">{{
                cleaner.workTeamName
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :rows="2" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listOrder,
  getOrder,
  delOrder,
  addOrder,
  updateOrder,
  workPlanCarCombo,
  workPlanPersonCombo,
} from "@/api/work/order";

import { getPersonCombo } from "@/api/base/person";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { treeselect } from "@/api/system/dept";

import { listEventFac } from "@/api/alarm/fac";

export default {
  name: "Order",
  components: {
    Treeselect,
  },
  dicts: ["order_status", "driver_deal_status", "cleaner_deal_status"],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 清运任务工单表格数据
      orderList: [],
      deptOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 时间范围
      daterangeDataTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined,
        carDeptId: undefined,
        managerDeptId: undefined,
        cleanerDeptId: undefined,
        orderNum: undefined,
        orderTime: undefined,
        facilityId: undefined,
        deviceId: undefined,
        orderStatus: undefined,
        teamSpanId: undefined,
        carId: undefined,
        carNum: undefined,
        driverId: undefined,
        driverName: undefined,
        driverDealStatus: undefined,
        driverDealTime: undefined,
        managerId: undefined,
        managerName: undefined,
        cleanerId: undefined,
        cleanerName: undefined,
        cleanerDealStatus: undefined,
        cleanerDealTime: undefined,
        createNickName: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderId: [{ required: true, message: "不能为空", trigger: "blur" }],
        deptId: [{ required: true, message: "部门不能为空", trigger: "blur" }],
        orderNum: [
          { required: true, message: "工单号不能为空", trigger: "blur" },
        ],
        orderTime: [
          { required: true, message: "工单生成时间不能为空", trigger: "blur" },
        ],
        facilityId: [
          { required: true, message: "设施不能为空", trigger: "blur" },
        ],
        deviceId: [
          { required: true, message: "设备不能为空", trigger: "blur" },
        ],
        orderStatus: [
          { required: true, message: "工单状态不能为空", trigger: "change" },
        ],
        teamSpanId: [
          { required: true, message: "车辆不能为空", trigger: "blur" },
        ],
        carNum: [
          { required: true, message: "车牌号不能为空", trigger: "blur" },
        ],
        driverId: [
          { required: true, message: "司机不能为空", trigger: "blur" },
        ],
        driverName: [
          { required: true, message: "司机姓名不能为空", trigger: "blur" },
        ],
        driverDealStatus: [
          {
            required: true,
            message: "司机处理结果不能为空",
            trigger: "change",
          },
        ],
        driverDealTime: [
          { required: true, message: "司机处理时间不能为空", trigger: "blur" },
        ],
        managerId: [
          { required: true, message: "主管不能为空", trigger: "blur" },
        ],
        managerName: [
          { required: true, message: "主管姓名不能为空", trigger: "blur" },
        ],
        cleanerId: [
          { required: true, message: "保洁不能为空", trigger: "blur" },
        ],
        cleanerName: [
          { required: true, message: "保洁姓名不能为空", trigger: "blur" },
        ],
        cleanerDealStatus: [
          {
            required: true,
            message: "保洁员处理结果不能为空",
            trigger: "change",
          },
        ],
        cleanerDealTime: [
          {
            required: true,
            message: "保洁员处理时间不能为空",
            trigger: "blur",
          },
        ],
      },
      facilityOptions: [],
      carOptions: [],
      cleanerOptions: [],
      managerOptions: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
    };
  },
  created() {
    this.getTreeselect();

    this.getList();
  },
  methods: {
    /** 告警 */
    getlistEventFac() {
      listEventFac().then((response) => {
        this.facilityOptions = response.data;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    /** 查询清运任务工单列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeDataTime && "" != this.daterangeDataTime) {
        this.queryParams.params["beginDataTime"] = this.daterangeDataTime[0];
        this.queryParams.params["endDataTime"] = this.daterangeDataTime[1];
      }
      listOrder(this.queryParams).then((response) => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: undefined,
        deptId: undefined,
        orderNum: undefined,
        orderTime: undefined,
        facilityId: undefined,
        deviceId: undefined,
        orderStatus: undefined,
        carId: undefined,
        carNum: undefined,
        driverId: undefined,
        driverName: undefined,
        driverDealStatus: undefined,
        driverDealTime: undefined,
        managerId: undefined,
        managerName: undefined,
        cleanerId: undefined,
        cleanerName: undefined,
        cleanerDealStatus: undefined,
        cleanerDealTime: undefined,
        remark: undefined,
        createTime: undefined,
        createBy: undefined,
        updateTime: undefined,
        updateBy: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeDataTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.orderId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getlistEventFac();
      this.open = true;
      this.title = "添加清运任务工单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const orderId = row.orderId || this.ids;
      getOrder(orderId).then((response) => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改清运任务工单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.orderId != null) {
            updateOrder(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addOrder(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal
        .confirm('是否确认删除"' + (row.orderName || "已勾选") + '"的数据项?')
        .then(() => {
          this.loading = true;
          return delOrder(orderIds);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "work/order/export",
        {
          ...this.queryParams,
        },
        `清运工单_${new Date().getTime()}.xlsx`
      );
    },
    changeCarDept(v) {
      if (v) {
        workPlanCarCombo({ deptId: v }).then((response) => {
          this.carOptions = response.data;
        });
      } else {
        this.carOptions = [];
      }
    },
    changeManagerDept(v) {
      if (v) {
        getPersonCombo({ deptId: v, personType: "manager" }).then(
          (response) => {
            this.managerOptions = response.data;
          }
        );
      } else {
        this.managerOptions = [];
      }
    },
    changeCleanerDept(v) {
      if (v) {
        workPlanPersonCombo({ deptId: v }).then((response) => {
          this.cleanerOptions = response.data;
        });
      } else {
        this.cleanerOptions = [];
      }
    },
    changeFacilityId(v) {
      if (v) {
        let facilityItem = this.facilityOptions.find(
          (item) => item.facilityId == v
        );
        // this.form.facilityId = facilityItem.facilityId;
        this.form.deviceId = facilityItem.deviceId;
      }
    },
    changeCarId(v) {
      if (v) {
        let carItem = this.carOptions.find((item) => item.teamSpanId == v);
        this.form.carNum = carItem.carNum;
        this.form.carId = carItem.carId;
        this.form.driverId = carItem.personId;
        this.form.driverName = carItem.personName;
      }
    },
    changeManagerId(v) {
      if (v) {
        let managerItem = this.managerOptions.find(
          (item) => item.personId == v
        );
        // this.form.managerId = managerItem.managerId;
        this.form.managerName = managerItem.personName;
      }
    },
    changeCleanerId(v) {
      if (v) {
        let cleanerItem = this.cleanerOptions.find(
          (item) => item.personId == v
        );
        // this.form.cleanerId = cleanerItem.cleanerId;
        this.form.cleanerName = cleanerItem.personName;
      }
    },
  },
};
</script>
